package com.app.community.service;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.app.community.mapper.PublishMapper;
import com.app.community.model.entity.AliyunClient;
import com.app.community.model.entity.ImgUploadResult;
import com.app.community.util.AliyunOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.FileEditor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.*;

/**
 * publish页面的逻辑层
 * @Date 2020/10/11 11:31
 **/
@Slf4j
@Service
public class PublishService {

    @Autowired
    PublishMapper publishMapper;

    // 上传工具
    AliyunOSSUtils ossUtils = new AliyunOSSUtils();
    // 获取阿里云账户
    AliyunClient ossClient = new AliyunClient();

    // 初始化返回结果
    ImgUploadResult result = new ImgUploadResult();

    // 图片地址列表
    String[] data = null;

    @Value("${file.upload.path}")
    private String filePath;

    /**
     * 发布文章(带有封面)
     */
    public void publishQuestion(Long questionId, String title, String article, String creator,String date,MultipartFile questionCoverPic, String summary) throws IOException {
        // 创建OSSClient实例。
        //OSS oss = new OSSClientBuilder().build(ossClient.getEndpoint(), ossClient.getAccessKeyId(), ossClient.getAccessKeySecret());

        String fileName = getFileName(questionCoverPic);

        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        questionCoverPic.transferTo(new File(filePath + "/" + fileName));
        String path = "/profile/" + fileName;

        // 关闭OSS。
        //oss.shutdown();

        publishMapper.publishQuestion(questionId, title, article, creator, date, path, summary);

    }


    /**
     * 发布文章没有封面
     */
    public void publishQuestion(Long questionId, String title, String article, String creator, String date, String summary) {
        publishMapper.publishQuestion(questionId, title, article, creator, date, null, summary);
    }


    /**
     * 上传图片到服务器,每次上传都会创建一个oss连接然后关闭，避免用户多次上传出现无法连接的错误
     */
    public String imgUpload(Map<String, MultipartFile> files, Long questionId) throws IOException {
        // 通过int向data添加数据，每次新上传图片，会刷新i的值，否则就会越界异常。同时js会更新页面图片的链接，每一次上传都JS都会从0开始取链接，不管之前的有没有删除
        int i = 0;

        // 创建OSSClient实例。
        //OSS oss = new OSSClientBuilder().build(ossClient.getEndpoint(), ossClient.getAccessKeyId(), ossClient.getAccessKeySecret());

        data = new String[files.size()];

        // 遍历files
        Iterator iterator = files.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            // 避免多次从map中获取效率太低，我们保存一个file
            MultipartFile file = (MultipartFile) entry.getValue();

            String fileName = getFileName(file);

            file.transferTo(new File(filePath + "/" + fileName));
            String path = "/profile/" + fileName;

            // 图片上传到阿里云
            //String path = ossUtils.uploadQuestionImgToOSS(oss, file.getInputStream(), questionId, fileName);

            data[i] = path;
            i++;
            log.info(fileName + "图片上传成功");
        }

        // 关闭OSS。
        //oss.shutdown();
        // 错误码设为0，即无错误
        result.setErrno(0);
        result.setData(data);
        return StringEscapeUtils.unescapeJson(JSONObject.toJSONString(result));
    }


    /**
     * 通过算法获得文件名
     */
    public String getFileName(MultipartFile file) {
        StringBuilder stringBuilder = new StringBuilder();
        // 文件名由后台生成，规则：文件名 = time + uuid
        UUID uuid = UUID.randomUUID();
        stringBuilder.append(uuid);
        // 获取当前time
        Long time = System.currentTimeMillis();
        stringBuilder.append(time.toString());
        // 获取后缀名
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        // 将后缀加入到文件名
        stringBuilder.append(suffix);
        return stringBuilder.toString();
    }

}
